$(function () {
    let goodsId = getQueryString("goodsId");
    let url = '../product/list';
    if (goodsId) {
        url += '?goodsId=' + goodsId;
    }
    $("#jqGrid").Grid({
        url: url, colModel: [{label: 'id', name: 'id', index: 'id', key: true, hidden: true}, {
            label: '商品', name: 'goodsName', index: 'goods_id', width: 120
        }, {
            label: '商品规格',
            name: 'specificationValue',
            index: 'goods_specification_ids',
            width: 100,
            formatter: function (value, options, row) {
                return value.replace(row.goodsName + " ", '');
            }
        }, {label: '商品序列号', name: 'goodsSn', index: 'goods_sn', width: 80}, {
            label: '商品库存', name: 'goodsNumber', index: 'goods_number', width: 80
        }, {
            label: '零售价格(元)', name: 'retailPrice', index: 'retail_price', width: 80
        }, // {label: '市场价格(元)', name: 'marketPrice', index: 'market_price', width: 80}
        ]
    });
});

let vm = new Vue({
    el: '#rrapp', data: {
        showList: true,
        title: null,
        product: {},
        ruleValidate: {
            goodsId: [{required: true, message: '商品不能为空', trigger: 'blur'}],
            goodsSn: [{required: true, message: '商品序列号不能为空', trigger: 'blur'}]
        },
        q: {
            goodsName: '',
        },
        goodss: [],
        attributes: [],
        attribute: [],
        specifications: [],
        type: '',
        disabled: false,
        goodsDisabled: false
    }, methods: {
        query: function () {
            vm.reload();
        }, add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.product = {};
            vm.attribute = [];
            vm.specifications = [];
            vm.getGoodss();
            vm.type = 'add';
            vm.disabled = false;
            vm.goodsDisabled = false;
        }, update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.type = 'update';
            vm.disabled = true;
            vm.goodsDisabled = true;
            vm.getInfo(id)
        }, changeGoods: function (opt) {
            let goodsId = opt.value;
            if (!goodsId) return;

            Ajax.request({
                url: "../goods/info/" + goodsId, async: true, successCallback: function (r) {
                    if (vm.type == 'add') {
                        vm.product.goodsSn = r.goods.goodsSn;
                        vm.product.goodsNumber = r.goods.goodsNumber;
                        vm.product.retailPrice = r.goods.retailPrice;
                        vm.product.marketPrice = r.goods.marketPrice;
                    }
                    vm.getAllAttributes(goodsId)
                }
            });
        }, saveOrUpdate: function (event) {
            let url = vm.product.id == null ? "../product/save" : "../product/update";
            //这里相同的商品规格要用逗号分割
            let gIds = [];
            vm.attributes.forEach((item, index) => {
                let childrenArr = []
                if (item.children) {
                    childrenArr = item.children.map((it) => {
                        return it.gsId;
                    });
                }
                let ids = [];
                vm.specifications.forEach((id, i) => {
                    if (childrenArr.indexOf(id) > -1) ids.push(id);
                });
                gIds.push(ids.join(","));
            });
            vm.product.goodsSpecificationIds = gIds.join("_");
            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.product),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });


        }, del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../product/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });


            });
        }, getInfo: function (id) {
            vm.attribute = [];
            vm.getGoodss();
            Ajax.request({
                url: "../product/info/" + id, async: true, successCallback: function (r) {
                    vm.product = r.product;
                    vm.product.goodsId = vm.product.goodsId + '';
                    vm.attributes = r.specification;
                    vm.specifications = vm.product.goodsSpecificationIds.split("_");
                    vm.specifications = vm.specifications.map(d => {
                        return Number(d)
                    });
                    //根据值取找到对应的商品规格
                    let ids = [];
                    vm.attributes.forEach((item, index) => {
                        let childrenArr = []
                        if (item.children) {
                            childrenArr = item.children.map((it) => {
                                return it.gsId;
                            });
                        }
                        vm.specifications.forEach((id, i) => {
                            if (childrenArr.indexOf(id) > -1) ids.push(item.id);
                        });
                    });
                    vm.attribute = Array.from(new Set(ids))
                }
            });
        }, reload: function (event) {
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'goodsName': vm.q.goodsName}, page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        }, handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        }, handleReset: function (name) {
            handleResetForm(this, name);
        }, getGoodss: function () {
            Ajax.request({
                url: "../goods/queryAll/", async: true, successCallback: function (r) {
                    vm.goodss = r.list;
                    vm.goodss.forEach((item) => {
                        item.id = item.id + '';
                    });
                    let goodsId = getQueryString("goodsId");
                    if (goodsId) {
                        vm.product.goodsId = Number(goodsId);
                        vm.goodsDisabled = true;
                    }
                }
            });
        }, //获取该商品的所有规格
        getAllAttributes: function (goodsId) {
            Ajax.request({
                url: "../specification/queryChildrenAll?sidx=sort_order",
                async: true,
                params: {'goodsId': goodsId},
                successCallback: function (r) {
                    vm.attributes = r.list;
                }
            });
        }
    }
});